<?php

/**
 * ADODB user
 *
 * @since ADD ADOdb Admin 0.0
 */
CLASS adodb_user EXTENDS session_user {

/**
 * The session key
 *
 * @since ADD ADOdb Admin
 */
   const SESSION_KEY = 'add_adodb_browser_adodb_user';

   const LOGIN_PAGE = 'login';

   protected $adodb;

/**
 * login function
 *
 * @author albertdiones@gmail.com
 */
   static function login(/* $type, $host, $username, $password, $database */) {
      list($type, $host, $username, $password, $database) = func_get_args();

      # Test Connect
      $test_connection = self::adodb_connect($type, $host, $username, $password, $database);


      if (!$test_connection)
         return false;

      $test_connection -> Close();

      $user = self::singleton();


      $user->type       = $type;
      $user->host       = $host;
      $user->username   = $username;
      $user->password   = $password;
      $user->database   = $database;


      return $user;
   }


   /**
    * adodb()
    *
    * @since ADD ADOdb Admin 0.0
    */
   public function adodb() {
      if (!isset($this->adodb)) {
         $this->adodb = self::adodb_connect($this->type, $this->host, $this->username, $this->password, $this->database, true);
      }
      return $this->adodb ;
   }

  /**
    * Static Connect
    *
    * @since ADD ADOdb Admin 0.0
    */
   public static function adodb_connect($type, $host, $username, $password, $database, $persistent = false) {

      $adodb = ADONewConnection($type);

      if (!$adodb)
         throw new e_user_input("Invalid type $type");

      if ( $adodb->Connect($host,$username,$password,$database) ) {
         $adodb -> SetFetchMode(add::config()->fetch_mode);
         return new adodb_wrapper( $adodb );
      }
      else {
         if (!filter_var($host,FILTER_VALIDATE_URL) && $database) {
            return self::adodb_connect($type, $host, $username, $password, null, $persistent);
         }
         throw new e_user_input("Failed to login (".$adodb->ErrorMsg().")");
      }
   }


}